package controllers

import (
	"github.com/gin-gonic/gin"
	"go-admin-official/guard"
	"go-admin-official/models"
	"go-admin-official/modules/auth"
	"go-admin-official/modules/config"
	"net/http"
)

func SignIn(ctx *gin.Context) {
	code, msg := auth.Login(ctx, guard.GetSignInParam(ctx))
	ctx.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  msg,
	})
}

func ApiSignIn(ctx *gin.Context) {
	code, msg, token, name := auth.ApiLogin(ctx, guard.GetSignInParam(ctx))

	ctx.JSON(http.StatusOK, gin.H{
		"code": code,
		"data": gin.H{
			"token":  token,
			"name":   name,
			"expire": config.Get().TokenSessionTime * 1000, // 毫秒
		},
		"msg": msg,
	})
}

func SignUp(ctx *gin.Context) {
	code, msg, num := auth.Register(guard.GetSignUpParam(ctx))
	ctx.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  msg,
		"data": gin.H{
			"num": num,
		},
	})
}

func Unique(ctx *gin.Context) {

	param := guard.GetUniqueParam(ctx)

	user := models.Users().Check(param.Type, param.Value)

	if user.Empty() {
		ctx.JSON(http.StatusOK, gin.H{
			"code": 400,
			"msg":  "user exists",
		})
		return
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "ok",
	})
}

func Logout(ctx *gin.Context) {
	code, msg := auth.Logout(ctx)
	ctx.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  msg,
	})
}
